package com.yuxin.common.security;

import com.yuxin.common.util.AntPathMatcher;
import com.yuxin.common.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author zehui.zeng
 * @date 13-3-17 下午6:06
 */
public class ResourceAccessFilter implements Filter{
    AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        Map user =  (Map)request.getSession().getAttribute("user");
        String url = request.getRequestURI();
        String ctx = request.getContextPath();
        request.setCharacterEncoding("UTF-8");
        // 判断是否权限访问
        if(ResourceAccessService.hasResPermission(user,ctx,url)){
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            response.setStatus(401);// 没有权限访问
            if(!StringUtils.hasText(request.getHeader("X-Requested-With"))){// 判断是否ajax请求
                if(user == null){
                    response.sendRedirect(ctx+"/index.jsp");
                }else{
                    response.sendRedirect(ctx+"/403.jsp");
                }
            }
        }
    }

    @Override
    public void destroy() {

    }


}
